package com.whfc.cncit.helmet.codec;

import com.whfc.cncit.constant.CncitConst;
import com.whfc.cncit.entity.CncitMsg;
import com.whfc.cncit.entity.CncitUpMsgPSA;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

import static com.whfc.cncit.constant.CncitConst.DELIMITER;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/7/16 19:14
 */
public class CncitMsgDecoder extends MessageToMessageDecoder<ByteBuf> {

    private Logger logger = LoggerFactory.getLogger(CncitMsgDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        if (!in.isReadable()) {
            return;
        }

        //解析,例如:$08,R,0001,#
        int totalLength = in.readableBytes();
        String data = in.readCharSequence(totalLength, CncitConst.UTF8).toString();
        logger.info("接收数据:{}", data);
        String[] dataArr = data.split(DELIMITER);
        if (dataArr.length > 0) {
                String cmd = dataArr[1];
                CncitMsgCodec codec = CncitMsgCodecFactory.create(cmd);
            if (codec != null) {
                if (CncitConst.UP_CMD_PSA.equals(cmd)) {
                    CncitUpMsgCodecPSA codecPSA = (CncitUpMsgCodecPSA) codec;
                    CncitUpMsgPSA message = codecPSA.decode(data);
                    if (message != null) {
                        out.add(message);
                    }
                } else {
                    CncitMsg message = codec.decode(data);
                    if (message != null) {
                        out.add(message);
                    }
                }

            }
        }
    }
}
